<!--
 * @Description: 
 * @Autor: Zhu_liangyu
 * @Date: 2020-07-14 17:19:38
--> 
<template>
  <div class="qc-websocket"></div>
</template>

<script>
import store from "@/store";
import WebSocketUtil from "@/utils/websocket-util";
export default {
  name: "WebSocket",
  data() {
    return {
      websockt: null
    };
  },
  // created() {
  //   this.initWebSocket();
  // },
  destroyed() {
    if (this.websockt != null) this.websockt.close(); //离开路由之后断开websocket连接
  },
  methods: {
    //初始化weosocket
    initWebSocket() {
      const wsuri =
        "ws://" +
        location.hostname +
        ":8869/future/webSocket.ws/" +
        store.getters.userId;
      this.websockt = new WebSocket(wsuri);
      this.websockt.onmessage = this.websocketonmessage;
      this.websockt.onopen = this.websocketonopen;
      this.websockt.onerror = this.websocketonerror;
      this.websockt.onclose = this.websocketclose;
    }, //链接成功
    websocketonopen() {
      console.log("WebSocket已连接;key: " + store.getters.userId);
    }, //连接建立失败重连
    websocketonerror() {
      this.initWebSocket();
    }, //数据接收
    websocketonmessage(e) {
      const redata = e.data;
      WebSocketUtil.handleMessage(redata);
    }, //数据发送
    websocketsend(Data) {
      this.websockt.send(Data);
    }, //关闭
    websocketclose(e) {
      console.log("断开连接", e);
    }
  }
};
</script>